<template>
  <div class="form-box">
    <el-form ref="formRef" :model="form" label-width="150px" :rules="rules">
      <el-card class="box-card">
        <el-row>
          <el-form-item label="カード番号：" prop="cardNo" label-width="120px">
            <el-select v-model="form.cardNo" placeholder="選択ください" style="width: 240px">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.maskedCardNumber"
                :value="item.value"
                :disabled="item.disabled"
              >
                <span style="float: left">{{ item.maskedCardNumber }}</span>
                <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">
                  {{ item.label }}
                </span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-card>

      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>カード利用情報</span>
          </div>
        </template>
        <el-row>
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <el-form-item label="カード処理区分：" prop="cardStatus" label-width="200px">
              <el-select
                v-model="form.cardStatus"
                placeholder="選択ください"
                style="width: 200px"
                @change="onCardStatusChange"
              >
                <el-option
                  v-for="cardStatus in cardStatuses"
                  :key="cardStatus.parentId"
                  :label="cardStatus.parentName"
                  :value="cardStatus.parentId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <el-form-item label="カード処理理由区分：" prop="subCardStatus" label-width="200px">
              <el-select
                v-model="form.subCardStatus"
                placeholder="選択ください"
                style="width: 200px"
                :disabled="!form.cardStatus"
              >
                <el-option
                  v-for="subCardStatus in subCardStatuses"
                  :key="subCardStatus.subId"
                  :label="subCardStatus.subName"
                  :value="subCardStatus.subId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <el-form-item label="カード処理年月日：" label-width="200px" prop="cardDoDate">
              <el-date-picker v-model="form.cardDoDate" type="date" placeholder="日付を選択ください" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <div class="button-container">
        <el-button type="primary" @click="submitForm">登録</el-button>
        <el-button @click="resetForm">リセット</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { selectStatusList, selectUserCardList, updateCardStatus } from '@/apis/user';
import { ElMessage } from 'element-plus';

const formRef = ref(null);
const form = reactive({
  cardNo: '',
  cardStatus: '',
  subCardStatus: '',
  cardDoDate: null,
});

const rules = reactive({
  cardNo: [
    {
      required: true,
      message: 'カード番号を選択ください。',
      trigger: 'change',
    },
  ],
  cardStatus: [
    {
      required: true,
      message: 'カード処理区分を選択ください',
      trigger: 'change',
    },
  ],
  subCardStatus: [
    {
      required: true,
      message: 'カード処理理由区分を選択ください',
      trigger: 'change',
    },
  ],
  cardDoDate: [
    {
      required: true,
      message: 'カード処理年月日を選択ください',
      trigger: 'change',
    },
  ],
});

const options = ref([]);
const cardStatuses = ref([]);
const subCardStatuses = ref([]);

onMounted(() => {
  fetchUserCardList();
  fetchStatusList();
});

function fetchUserCardList() {
  selectUserCardList()
    .then((res) => {
      if (res.data.code === 200) {
        options.value = res.data.data.map(item => {
          const maskedCardNumber = `${item.cardNumber.slice(0, 4)}--------${item.cardNumber.slice(-4)}`;
          return {
            value: item.cardNumber,
            label: item.cardStatus === 0 ? '利用可' : '審査中',
            disabled: item.cardStatus === 0 ? false : true,
            maskedCardNumber: maskedCardNumber
          };
        });
      }
    })
    .catch((error) => {
      ElMessage.error('ユーザー情報を取得中にエラーが発生しました。');
    });
}

function fetchStatusList() {
  selectStatusList()
    .then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        const groupedData = groupByParentId(data);
        cardStatuses.value = Object.keys(groupedData).map((parentId) => ({
          parentId: parseInt(parentId),
          parentName: groupedData[parentId][0].parentName,
          SubCardStatues: groupedData[parentId],
        }));
      }
    })
    .catch((error) => {
      ElMessage.error('ユーザー情報を取得中にエラーが発生しました。');
    });
}

function groupByParentId(data) {
  return data.reduce((acc, curr) => {
    if (!acc[curr.parentId]) {
      acc[curr.parentId] = [];
    }
    acc[curr.parentId].push(curr);
    return acc;
  }, {});
}

const onCardStatusChange = (parentId) => {
  const selectedCard = cardStatuses.value.find((status) => status.parentId === parentId);
  if (selectedCard) {
    subCardStatuses.value = selectedCard.SubCardStatues;
  } else {
    subCardStatuses.value = [];
  }
  form.subCardStatus = '';
};

const submitForm = () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('Submitting form:', form); // 打印表单数据用于调试
      const formData = {
        cardNumber: form.cardNo,
        cardApplyType: form.cardStatus,
        cardReasonType: form.subCardStatus,
        cardSubmitDate: form.cardDoDate,
      };
      console.log('formData=======>',formData)
      updateCardStatus(formData).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success('審査登録しました！');
          // 刷新列表
          fetchUserCardList();
          fetchStatusList();
          resetForm();
        } else {
          ElMessage.error('審査登録できません。');
        }
      }).catch((error) => {
        ElMessage.error('審査登録にエラーが発生しました。');
        console.error('審査登録エラー:', error);
      });
    } else {
      console.log('error submit!');
    }
  });
};

const resetForm = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  subCardStatuses.value = [];
  form.cardStatus = '';
  form.subCardStatus = '';
  form.cardDoDate = null;
};
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 10px;
  > div {
    > div {
      text-align: left;
    }
  }
}
.button-container {
  display: flex;
  justify-content: center; /* 水平居中对齐 */
  margin-top: 20px; /* 添加一些上边距，使按钮和表单之间有间距 */
}
</style>
